<template>
  <div class="departments-container">
    <div class="page-header">
      <h2 class="page-title">用户列表</h2>
      <el-button type="primary" @click="handleAddUser">
        <el-icon><Plus /></el-icon>添加用户
      </el-button>
    </div>

    <el-card class="content-card">
      <el-table
        v-loading="loading"
        :data="userList"
        border
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="60" />
        <el-table-column prop="username" label="用户名" min-width="120" />
        <el-table-column prop="name" label="姓名" min-width="100" />
        <el-table-column label="邮箱" min-width="180" show-overflow-tooltip>
          <template #default="scope">
            <el-tooltip
              :content="scope.row.email"
              placement="top"
              :disabled="scope.row.email && scope.row.email.length < 20"
            >
              <span>{{ scope.row.email }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="部门" min-width="180" max-width="240">
          <template #default="scope">
            <el-tooltip 
              v-if="scope.row.department_path && scope.row.department_path.length > 25"
              :content="scope.row.department_path || '未分配'" 
              placement="top"
            >
              <el-tag 
                :type="getDepartmentTagType(scope.row.department_name)"
                :effect="'light'"
                size="small"
                class="dept-path-tag"
              >
                {{ formatDepartmentPath(scope.row.department_path) || '未分配' }}
              </el-tag>
            </el-tooltip>
            <el-tag 
              v-else
              :type="getDepartmentTagType(scope.row.department_name)"
              :effect="'light'"
              size="small"
              class="dept-path-tag"
            >
              {{ formatDepartmentPath(scope.row.department_path) || '未分配' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="角色" min-width="120">
          <template #default="scope">
            <div class="role-tags-wrapper">
              <el-tag 
                v-for="role in scope.row.roles" 
                :key="role.id" 
                class="role-tag"
                type="info"
              >
                {{ role.name }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.status === '启用' ? 'success' : 'danger'">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" min-width="160">
          <template #default="scope">
            {{ formatDateTime(scope.row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160" fixed="right">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              @click="handleEditUser(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDeleteUser(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 用户表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加用户' : '编辑用户'"
      width="500px"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userFormRules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="userForm.name" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="dialogType === 'add'">
          <el-input v-model="userForm.password" type="password" />
        </el-form-item>
        <el-form-item label="部门" prop="department_id">
          <div class="parent-dept-selector">
            <el-tooltip 
              :content="userForm.department_path || '请选择部门'" 
              placement="top"
              :disabled="!userForm.department_path || userForm.department_path.length <= 25"
            >
              <el-input 
                v-model="userForm.department_path" 
                placeholder="请选择部门" 
                readonly
                @click="showDeptTree = true"
                suffix-icon="ArrowDown"
              >
                <template #append>
                  <el-button 
                    v-if="userForm.department_id" 
                    @click.stop="clearDepartmentSelection" 
                    icon="Close"
                  />
                </template>
              </el-input>
            </el-tooltip>
            
            <div v-if="showDeptTree" class="parent-tree-dropdown">
              <div class="tree-search">
                <el-input 
                  v-model="deptSearchText" 
                  placeholder="搜索部门" 
                  clearable
                  prefix-icon="Search"
                  @input="filterDeptTree"
                />
              </div>
              <div class="parent-tree-container">
                <el-scrollbar height="250px">
                  <el-tree
                    ref="deptTreeRef"
                    :data="departmentTree"
                    :props="deptTreeProps"
                    :filter-node-method="filterDeptNode"
                    node-key="dept_id"
                    highlight-current
                    :current-node-key="userForm.department_id"
                    @node-click="handleDeptNodeClick"
                    :expand-on-click-node="false"
                    :check-strictly="true"
                  >
                    <template #default="{ node, data }">
                      <span class="compact-tree-node">
                        <span :class="{'selected-dept': userForm.department_id === data.dept_id}">
                          {{ data.dept_name }}
                        </span>
                      </span>
                    </template>
                  </el-tree>
                </el-scrollbar>
              </div>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="角色" prop="role_ids">
          <el-select v-model="userForm.role_ids" multiple placeholder="请选择角色">
            <el-option 
              v-for="role in roleList" 
              :key="role.id" 
              :label="role.name" 
              :value="role.id" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="userForm.status"
            :active-value="'启用'"
            :inactive-value="'禁用'"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitUserForm">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getUserList, createUser, updateUser, deleteUser } from '../api/user'
import { getRoleList } from '../api/user'
import { getDepartmentList, getDepartmentTree } from '../api/department'
import { formatDateTime } from '../utils/format'
import { Folder, FolderOpened } from '@element-plus/icons-vue'

// 部门树相关变量
const showDeptTree = ref(false)
const deptSearchText = ref('')
const deptTreeRef = ref(null)

// 部门树配置
const deptTreeProps = {
  children: 'children',
  label: 'dept_name'
}

// 过滤部门树节点
const filterDeptNode = (value, data) => {
  if (!value) return true
  return data.dept_name.toLowerCase().includes(value.toLowerCase())
}

// 过滤部门树
const filterDeptTree = (val) => {
  deptTreeRef.value?.filter(val)
}

// 点击部门树节点
const handleDeptNodeClick = (data) => {
  userForm.department_id = data.dept_id
  userForm.department_path = buildDepartmentPath(data, departmentTree.value)
  showDeptTree.value = false
}

// 清除部门选择
const clearDepartmentSelection = (event) => {
  if (event) {
    event.stopPropagation()
  }
  userForm.department_id = null
  userForm.department_path = ''
  if (deptTreeRef.value) {
    deptTreeRef.value.setCurrentKey(null)
  }
}

// 监听点击事件，点击外部关闭树形选择器
const handleClickOutside = (event) => {
  if (showDeptTree.value) {
    const deptSelector = document.querySelector('.parent-dept-selector')
    if (deptSelector && !deptSelector.contains(event.target)) {
      showDeptTree.value = false
    }
  }
}

// 用户列表数据
const loading = ref(false)
const userList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const roleList = ref([])
const departmentTree = ref([])

// 根据部门名称获取标签类型（颜色）
const getDepartmentTagType = (departmentName) => {
  if (!departmentName) return 'info'; // 未分配部门用灰色
  
  // 使用部门名称的哈希值来决定颜色类型，保证同一部门总是同一颜色
  const hash = hashCode(departmentName);
  const tagTypes = ['primary', 'success', 'warning', 'danger', ''];
  const index = Math.abs(hash) % tagTypes.length;
  return tagTypes[index];
}

// 简单的字符串哈希函数
const hashCode = (str) => {
  let hash = 0;
  if (!str || str.length === 0) return hash;
  
  for (let i = 0; i < str.length; i++) {
    const char = str.charCodeAt(i);
    hash = ((hash << 5) - hash) + char;
    hash = hash & hash; // Convert to 32bit integer
  }
  
  return hash;
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchUserList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchUserList()
}

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add') // 'add' 或 'edit'
const userFormRef = ref(null)
const userForm = reactive({
  id: '',
  username: '',
  name: '',
  email: '',
  password: '',
  role_ids: [],
  department_id: null,
  department_path: '',
  status: '启用'
})

// 表单验证规则
const userFormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  role_ids: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
}

// 获取角色列表
const fetchRoleList = async () => {
  try {
    const response = await getRoleList({ page: 1, limit: 100 })
    if (response && response.data) {
      roleList.value = response.data.items
    }
  } catch (error) {
    console.error('获取角色列表失败:', error)
    ElMessage.error('获取角色列表失败')
  }
}

// 级联选择器配置已替换为树形选择器

// 递归查找选中的部门
const findSelectedDepartment = (deptId, tree) => {
  for (const dept of tree) {
    if (dept.dept_id === deptId) {
      userForm.department_path = buildDepartmentPath(dept, departmentTree.value);
      return dept;
    }
    if (dept.children && dept.children.length > 0) {
      const found = findSelectedDepartment(deptId, dept.children);
      if (found) return found;
    }
  }
  return null;
}

// 获取部门列表
const fetchDepartmentList = async () => {
  try {
    // 获取部门树结构而非平铺列表
    const response = await getDepartmentTree()
    if (response && response.data) {
      departmentTree.value = response.data.items
      // 部门树加载后，刷新用户列表以更新部门路径
      if (userList.value.length > 0) {
        updateUserDepartmentPaths();
      }
    }
  } catch (error) {
    console.error('获取部门列表失败:', error)
    ElMessage.error('获取部门列表失败')
  }
}

// 更新用户列表中的部门路径
const updateUserDepartmentPaths = () => {
  if (!departmentTree.value || departmentTree.value.length === 0) return;
  
  userList.value.forEach(user => {
    if (user.department_id) {
      const dept = findDepartmentById(user.department_id, departmentTree.value);
      if (dept) {
        user.department_path = buildDepartmentPath(dept, departmentTree.value);
      }
    }
  });
}

// 格式化部门路径，处理过长文本
const formatDepartmentPath = (path) => {
  if (!path) return '未分配';
  // 如果路径太长，截断并添加省略号
  if (path.length > 25) {
    return path.substring(0, 22) + '...';
  }
  return path;
}

// 获取用户列表
const fetchUserList = async () => {
  loading.value = true
  try {
    const response = await getUserList({
      page: currentPage.value,
      limit: pageSize.value
    })
    
    // 直接从响应中获取 data 字段
    if (response && response.data) {
      // 获取用户列表
      const users = response.data.items;
      
      // 如果部门树已经加载，则使用部门树构建部门路径
      if (departmentTree.value && departmentTree.value.length > 0) {
        users.forEach(user => {
          if (user.department_id) {
            const dept = findDepartmentById(user.department_id, departmentTree.value);
            if (dept) {
              user.department_path = buildDepartmentPath(dept, departmentTree.value);
            }
          }
        });
      }
      
      userList.value = users;
      total.value = response.data.total;
    }
    loading.value = false
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
    loading.value = false
  }
}

// 构建部门的完整路径
const buildDepartmentPath = (dept, deptTree) => {
  if (!dept) return '';
  
  const pathParts = [];
  pathParts.push(dept.dept_name); // 当前部门名称
  
  // 尝试查找父级部门并构建完整路径
  let parentId = dept.parent_id;
  while (parentId) {
    const parent = findDepartmentById(parentId, deptTree);
    if (parent) {
      pathParts.unshift(parent.dept_name); // 添加到路径开头
      parentId = parent.parent_id;
    } else {
      break;
    }
  }
  
  // 用斜杠连接
  return pathParts.join('/');
}

// 查找指定ID的部门
const findDepartmentById = (deptId, tree) => {
  for (const dept of tree) {
    if (dept.dept_id === deptId) {
      return dept;
    }
    if (dept.children && dept.children.length > 0) {
      const found = findDepartmentById(deptId, dept.children);
      if (found) return found;
    }
  }
  return null;
}

// 添加用户
const handleAddUser = () => {
  dialogType.value = 'add'
  resetUserForm()
  dialogVisible.value = true
}

// 编辑用户
const handleEditUser = (row) => {
  dialogType.value = 'edit'
  resetUserForm()
  
  userForm.id = row.id
  userForm.username = row.username
  userForm.name = row.name
  userForm.email = row.email
  userForm.status = row.status
  userForm.department_id = row.department_id
  userForm.department_path = row.department_path
  
  // 设置角色ID
  userForm.role_ids = row.roles.map(role => role.id)
  
  dialogVisible.value = true
}

// 删除用户
const handleDeleteUser = (row) => {
  ElMessageBox.confirm(
    `确定要删除用户 ${row.username} 吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await deleteUser(row.id)
      ElMessage.success('删除成功')
      fetchUserList()
    } catch (error) {
      console.error('删除用户失败:', error)
      ElMessage.error('删除用户失败')
    }
  }).catch(() => {
    // 取消删除
  })
}

// 重置表单
const resetUserForm = () => {
  userForm.id = ''
  userForm.username = ''
  userForm.name = ''
  userForm.email = ''
  userForm.password = ''
  userForm.role_ids = []
  userForm.department_id = null
  userForm.department_path = ''
  userForm.status = '启用'
  
  if (userFormRef.value) {
    userFormRef.value.resetFields()
  }
}

// 提交表单
const submitUserForm = async () => {
  if (!userFormRef.value) return
  
  await userFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 准备需要发送的表单数据
        const formData = {
          name: userForm.name,
          email: userForm.email,
          role_ids: userForm.role_ids,
          department_id: userForm.department_id,
          status: userForm.status
        };
        
        // 创建用户时需要额外的字段
        if (dialogType.value === 'add') {
          formData.username = userForm.username;
          formData.password = userForm.password;
          
          await createUser(formData);
          ElMessage.success('添加成功');
        } else {
          // 更新用户
          await updateUser(userForm.id, formData);
          ElMessage.success('更新成功');
        }
        
        dialogVisible.value = false;
        fetchUserList();
      } catch (error) {
        console.error('提交用户表单失败:', error);
        ElMessage.error(error.response?.data?.detail || '操作失败');
      }
    }
  });
}

// 页面加载顺序
onMounted(async () => {
  document.addEventListener('click', handleClickOutside)
  
  // 先获取部门树
  await fetchDepartmentList()
  // 再获取用户列表和角色列表
  await fetchUserList()
  await fetchRoleList()
})

// 组件卸载前移除事件监听
onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
})
</script>

<style lang="scss" scoped>
.departments-container {
  padding: 20px;
  margin: 0;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
  }
  
  .pagination-wrapper {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  
  .role-tags-wrapper {
    display: flex;
    flex-wrap: wrap;
  }
  
  .role-tag {
    margin-right: 5px;
    margin-bottom: 4px;
  }
  
  /* 部门标签样式 */
  :deep(.el-tag) {
    font-weight: 500;
    border-radius: 4px;
  }
  
  .dept-path-tag {
    max-width: 240px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    font-size: 12px;
  }
  
  /* 部门选择器样式 */
  .parent-dept-selector {
    position: relative;
    width: 100%;
    
    .el-input {
      width: 100%;
    }
    
    .parent-tree-dropdown {
      position: absolute;
      top: 100%;
      left: 0;
      right: 0;
      background-color: #fff;
      border: 1px solid #e4e7ed;
      border-radius: 4px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      z-index: 100;
      margin-top: 5px;
      width: 100%;
      
      .tree-search {
        padding: 8px;
        border-bottom: 1px solid #ebeef5;
        background-color: #f5f7fa;
      }
      
      .parent-tree-container {
        background-color: #fff;
        
        :deep(.el-tree) {
          padding: 5px;
          
          .el-tree-node__content {
            height: 24px; /* Compact height */
            padding-left: 8px !important;
            
            &:hover {
              background-color: #f5f7fa;
            }
          }
          
          .is-current > .el-tree-node__content {
            background-color: #ecf5ff;
            color: #409EFF;
          }
          
          /* Reduce spacing between nodes */
          .el-tree-node {
            padding-bottom: 0;
          }
          
          /* Adjust the expand arrow position */
          .el-tree-node__expand-icon {
            padding: 4px;
          }
          
          /* Smaller font size */
          .el-tree-node__label {
            font-size: 13px;
          }
          
          /* Adjust indentation for better hierarchy visualization */
          .el-tree-node__children {
            padding-left: 16px;
          }
        }
        
        .selected-dept {
          color: #409EFF;
          font-weight: 500;
          font-size: 13px; /* Smaller font size */
        }
        
        .compact-tree-node {
          display: flex;
          align-items: center;
          font-size: 13px;
          line-height: 1.2;
          padding: 2px 0;
        }
      }
    }
  }
}
</style> 